{% extends 'base.html' %}
{% block head_block %}
    <title>第一个页面布局</title>
    <script src="../static/resource/js/world.js"></script>
    <style>
        * {
            padding: 0;
            margin: 0;
        }

        #root {
            display: flex;
            box-sizing: border-box;
            width: 100%;
            flex-grow: 1;
            max-height: 88%;
        }

        #main_block {
            box-sizing: border-box;
            /* border: solid 1px #000000; */
            display: flex;
            width: 100%;
            /* 主轴水平排列 */
            flex-direction: row;
            /* 主轴水平平均分布 */
            justify-content: space-evenly;
            /* 交叉轴纵向拉伸：不行，否则标签滚动条就加不上了 */
            /* align-items: stretch; */
        }

        #main_block > * {
            box-sizing: border-box;
            /* background-color: #99a9bf; */
            /* padding: 10px; */
            /* border: solid 1px rgba(84, 215, 255, 0.89); */
            /* background-clip: content-box; */
            flex-shrink: 1;
            height: 95%;
        }

        #left_block, #mid_block, #right_block {
            display: flex;
            flex-direction: column;
            justify-content: space-between;
        }

        #left_block > * {
            height: 31%;
        }

        #left_block > *, #mid_block > *, #right_block > * {
            width: 100%;
            flex-shrink: 1;
            border: solid 1px rgba(84, 215, 255, 0.89);
            padding: 5px;
            background-color: #011838;
            box-sizing: border-box;
        }

        #mid_block :first-child {
            height: 55%;
        }

        #mid_block :last-child {
            height: 40%;
        }

        #right_block {
            border: solid 1px rgba(84, 215, 255, 0.89);
            justify-content: center;
            align-items: center;
        }

        #right_block > * {
            border: 0;
        }

        #right_block_u {
            height: 130px;
            width: 100%;
            flex-shrink: 0;
            box-sizing: border-box;
        }

        #right_block_d {
            overflow: auto;
            box-sizing: border-box;
        }

        #right_block_d > * {
            background-color: #02335a;
            /* border: solid 1px rgba(255, 255, 255, 0.89); */
            margin: 10px auto 0 auto;
            padding: 5px;
            box-sizing: border-box;
            font-size: 10px;
            text-align: justify;
        }

        #right_block_d::-webkit-scrollbar {
            display: none; /* Chrome Safari */
        }

        #right_block_d {
            scrollbar-width: none; /* firefox */
            -ms-overflow-style: none; /* IE 10+ */
            overflow-x: hidden;
            overflow-y: auto;
        }

        .user_profile {
            align-items: center;
        }

        /* 按钮形状 */
        .parallelogram {
            width: 20%;
            height: 80%;
            transform: skewX(-15deg);
            border: solid 2px rgba(33, 176, 220, 0.76);
            display: flex;
            justify-content: center;
        }

        .parallelogram > div {
            transform: skewX(15deg);
            margin: auto auto;
            color: #FFFFFF;
        }

        .parallelogram:hover {
            background: rgba(85, 192, 226, 0.79);
            cursor: pointer;
        }

        /* 按钮组设置 */
        #btn_group {
            display: flex;
            width: 95%;
            margin-top: 5px;
            margin-left: auto;
            margin-right: auto;
        }

        #btn_group > * {
            flex-grow: 1;
            height: 25px;
            color: rgb(148, 148, 148);
            display: flex;
            align-items: center;
            justify-content: center;
        }

        #btn_group > *:hover {
            background-color: rgb(125, 191, 255);
        }

        #btn_group > *:focus {
            background-color: #3f9ffc;
            color: #FFFFFF;
        }

        /* 各个统计数据-左半拉 */
    </style>
{% endblock head_block %}

{% block name_block %}
    整体数据展示
{% endblock %}

{% block body_block %}
    <div id="root">
        <div style="width: 150px;height: 25px;position: absolute; top: 7px; left: 62vw;">
            <!--
            <el-dropdown>
                <span class="el-dropdown-link" style="color: #FFFFFF;font-size: 30px">
                    <i class="bi bi-box-arrow-right"></i>
                </span>
                <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item key="1" onclick="pageSelect('1')">
                        数据分析页面
                    </el-dropdown-item>
                    {#                    <el-dropdown-item key="2" onclick="pageSelect('2')">#}
                    {#                        数据总体分布#}
                    {#                    </el-dropdown-item>#}
                    <el-dropdown-item key="3" onclick="pageSelect('3')">
                        主题聚类页面
                    </el-dropdown-item>
                    <el-dropdown-item key="4" onclick="pageSelect('4')">
                        评论回复页面
                    </el-dropdown-item>
                </el-dropdown-menu>
            </el-dropdown>
            -->
        </div>
        <div id="main_block">
            <div id="left_block" style="width: 25%">
                <div id="pages" style="height: 40px;border: 0; background-color: transparent;display: flex">
                    <el-button-group style="flex: 1">
                        <el-button @click.native="pageSelect('1')" type="primary" size="medium">内容分析</el-button>
                        <el-button @click.native="pageSelect('2')" type="primary" size="medium">主题分析</el-button>
                        <el-button @click.native="pageSelect('3')" type="primary" size="medium">评论回复</el-button>
                        <el-button @click.native="pageSelect('4')" type="primary" size="medium">自动爬虫</el-button>
                    </el-button-group>
                </div>
                <div id="left_block_u" style="display: flex;flex-direction: column">
                    <div style="height: 30px;width: 100%;border: 0;color: #f9fafc;background: linear-gradient(to right, #3053a4 30%, #0d224e 70%);text-align: left;
                    display: flex;align-items: center;justify-content: space-between">
                        <div style="margin-left: 10px">基本数据指标</div>
                        <i style="font-size: 20px;margin-right:20px;" class="bi bi-download"
                           @click="download(1)"></i>
                    </div>
                    <el-button-group id="btn_group" v-model="basic_data.key">
                        <el-button @click="selectOption('month')" value="month">月环比</el-button>
                        <el-button @click="selectOption('season')" value="season">季环比</el-button>
                        <el-button @click="selectOption('half_year')" value="half_year">半年环比</el-button>
                        <el-button @click="selectOption('year')" value="year">年环比</el-button>
                    </el-button-group>
                    <div v-loading="!isLoaded.basic"
                         element-loading-text="数据加载中"
                         element-loading-background="rgba(0, 0, 0,0 )"
                         style="display: flex;justify-content: space-evenly;flex-grow: 1;align-items: center;">
                        <template v-for="instance in basic_data.datas">
                            <!-- template只用于和v-for搭配 -->
                            <!-- TODO：这里的上升下降要比较一下 -->
                            <div style="width: 30%; height: 90%;">
                                <div style="width: 100%;height: 80%;background-color: rgba(2,51,90);
                                display: flex;justify-content: center;align-items: center;font-size: 15px;color: #FFFFFF">
                                    <div style="height: 60%;width: 80%;display: flex;flex-direction: column;justify-content: center;align-items: center">
                                        <div v-text="'总'+instance.name+'数'"></div>
                                        <div style="display: flex;align-items: flex-end;margin-top: 5px">
                                            <div v-text="instance.data.sum" style="font-size: 20px"></div>
                                            <div v-text="instance.data.unit"></div>
                                        </div>
                                    </div>
                                </div>
                                <div style="width: 100%;height: 20%;border-top: solid 1px rgb(185,185,185);background-color: rgba(2,51,90);
                                     font-size: 10px;color: #FFFFFF;display: flex;justify-content: center;align-items: center">
                                    <div v-text="basic_data.kv[basic_data.key]+': 上升'+instance.data.trend+'%'"></div>
                                </div>
                            </div>
                        </template>
                    </div>
                </div>
                <div id="left_block_m" style="display: flex;flex-direction: column;">
                    <div style="height: 30px;width: 100%;border: 0;color: #f9fafc;background: linear-gradient(to right, #3053a4 30%, #0d224e 70%);text-align: left;
                    display: flex;align-items: center;">
                        <div style="margin-left: 10px">情感占比图</div>
                    </div>
                    <div v-loading="!isLoaded.sentiment" id="sentment_porporation"
                         element-loading-text="数据加载中"
                         element-loading-background="rgba(0, 0, 0,0 )"
                         style="flex-grow: 1;width: 100%;border: 0"></div>
                </div>
                <div id="left_block_d" style="display: flex;flex-direction: column;">
                    <div style="height: 30px;width: 100%;border: 0;color: #f9fafc;background: linear-gradient(to right, #3053a4 30%, #0d224e 70%);text-align: left;
                    display: flex;align-items: center">
                        <div style="margin-left: 10px">情绪占比图</div>
                    </div>
                    <div v-loading="!isLoaded.emotion" id="emotion_porporation"
                         element-loading-text="数据加载中"
                         element-loading-background="rgba(0, 0, 0, 0)"
                         style="flex-grow: 1;flex-shrink: 1;width: 100%;border: 0"></div>
                </div>
            </div>
            <div id="mid_block" style="width: 40%">
                <div id="mid_block_u" style="display: flex;flex-direction: column;">
                    <div style="padding: 0;height: 30px;width: 100%;border: 0;color: #f9fafc;background: linear-gradient(to right, #3053a4 30%, #0d224e 70%);text-align: left;
                    display: flex;align-items: center; justify-content: space-between">
                        <div style="height:20px; margin-left:10px;">全球舆论地图</div>
                        <i style="font-size: 20px;margin-right:20px; margin-bottom: 10px" class="bi bi-download"
                           @click="download(2)"></i>
                    </div>
                    <!--
                    <div id="hw_map" style="width: 100%; height: calc(100% - 30px)">
                        <div id="world_map" style="flex-grow: 1;width: 100%;border: 0"></div>
                    </div>
                    -->
                    <div v-loading="!isLoaded.map" id="world_map"
                         element-loading-text="数据加载中"
                         element-loading-background="rgba(0, 0, 0,0 )" style="flex-grow: 1;width: 100%;border: 0"></div>
                </div>
                <div id="mid_block_d" style="display: flex;flex-direction: column;">
                    <div style="height: 30px;width: 100%;border: 0;color: #f9fafc;background: linear-gradient(to right, #3053a4 30%, #0d224e 70%);text-align: left;
                    display: flex;align-items: center;justify-content: space-between">
                        <div style="height:20px; margin-left:10px">事件走势图</div>
                        <i style="font-size: 20px;margin-right:20px;margin-bottom: 15px" class="bi bi-download"
                           @click="download(3)"></i>
                    </div>
                    <div v-loading="!isLoaded.event" id="event_trend"
                         element-loading-text="数据加载中"
                         element-loading-background="rgba(0, 0, 0,0 )"
                         style="flex-grow: 1;width: 100%;border: 0"></div>
                </div>
            </div>
            <div id="right_block" style="width: 25%">
                <div id="right_block_u" style="display: flex; flex-direction: column;">
                    <div style="height: 30px;width: 100%;border: 0;color: #f9fafc;background: linear-gradient(to right, #3053a4 30%, #0d224e 70%);text-align: left;
                    display: flex;align-items: center;justify-content: space-between">
                        <template style="display: flex;">
                            <div v-text="'热点信息（'+date+'）'" style="margin-left: 10px"></div>
                        </template>
                        <i style="font-size: 20px;margin-right:20px;" class="bi bi-download"
                           @click="download(4)"></i>
                    </div>
                    <div style="display: flex; align-items: center;">
                        <el-date-picker
                                id=""
                                size="small"
                                style="flex: 1; margin: 5px"
                                v-model="dateRange"
                                type="daterange"
                                range-separator="至"
                                start-placeholder="开始日期"
                                end-placeholder="结束日期"
                                @change="updateQueryString">
                        </el-date-picker>
                        <!--<el-button @click.native="pageSelect('4')" type="primary" size="medium">自动爬虫</el-button>-->
                        <el-button @click.native="updateDataByDate" type="primary" size="medium">浏览数据</el-button>
                    </div>
                    <div style="margin-top: 10px;display: flex;justify-content: space-evenly;align-items: center;flex-grow: 1;user-select:None">
                        <div class="btn parallelogram" value="like_cnt" @click="handleItemClick('like_cnt')">
                            <div>点赞排序</div>
                        </div>
                        <div class="btn parallelogram" value="comment_cnt" @click="handleItemClick('comment_cnt')">
                            <div>评论排序</div>
                        </div>
                        <div class="btn parallelogram" value="transfer_cnt" @click="handleItemClick('transfer_cnt')">
                            <div>转发排序</div>
                        </div>
                        <div class="btn parallelogram" value="share_cnt" @click="handleItemClick('share_cnt')">
                            <div>引用排序</div>
                        </div>
                    </div>
                </div>
                <div v-loading="!isLoaded.blogs" element-loading-text="数据加载中"
                     element-loading-background="rgba(0, 0, 0, 0)"
                     id="right_block_d" style="flex-grow: 1;border: 0">
                    <!-- TODO：从vue中取数据 -->
                    <template v-for="instance in blogs[orderBy]" style="border: 0">
                        <!-- TODO：限制一下名字的长度、计算一下粉丝的数目，转成M的格式 -->
                        <div style="min-height: 150px;width: 97%;display: flex;flex-direction:column;justify-content: stretch;color: #ffffff">
                            <div class="user_profile" id="user_profile_"
                                 style="display: flex;justify-content: space-between;height: 45px;width: 95%">
                                <div style="display: flex;justify-content: start;align-items: center">
                                    <img src="/static/resource/pics/lani.jpg" alt=""
                                         style="height: 30px;width: 30px;border-radius:100%">
                                    <span v-text="instance.userName" style="margin: 0 5px">Adam Schefter</span>
                                </div>
                                <div style="display: flex;">
                                    <div v-text="formatFansValue(instance.fans_cnt)"></div>
                                    <div>M</div>
                                    <i class="bi bi-person-plus"></i>
                                </div>
                                <i class="bi bi-globe" style="font-style: normal">
                                    <span v-text="instance.nation" style="margin-left: 5px">NewYork</span>
                                </i>
                            </div>
                            <div v-text="instance.blog_ctn" id="comment_{{ idx }}"
                                 style="width: 80%;margin: 0 auto;text-overflow: ellipsis">
                                Lorem ipsum dolor sit amet, consectetur adipiscing elit.
                                Aenean euismod bibendum laoreet. Proin gravida dolor sit
                            </div>
                            <div v-text="'发布时间: '+instance.date+' '+instance.time" id="desc_{{ idx }}"
                                 style="flex-grow: 1;width: 80%;margin: 5px auto">
                                发布时间: 2023-10-14 14:00
                            </div>
                            <div id="footer_{{ idx }}"
                                 style="height: 30px;display: flex;flex-direction: row;justify-content: space-between;width: 80%;margin: 0 auto;">
                                <i class="bi bi-hand-thumbs-up-fill">
                                    <span v-text="instance.like_cnt"
                                          style="margin-left: 5px;font-style: normal">600</span>
                                </i>
                                <i class="bi bi-chat-dots">
                                    <span v-text="instance.comment_cnt"
                                          style="margin-left: 5px;font-style: normal">600</span>
                                </i>
                                <i class="bi bi-repeat">
                                    <span v-text="instance.transfer_cnt"
                                          style="margin-left: 5px;font-style: normal">600</span>
                                </i>
                                <i class="bi bi-share">
                                    <span v-text="instance.share_cnt"
                                          style="margin-left: 5px;font-style: normal">600</span>
                                </i>
                            </div>
                        </div>
                    </template>
                </div>
            </div>
        </div>
    </div>
    <!-- vue数据绑定 -->
    <script>
        /* 推文排序 */
        const blogs_dict = {
            'like': '点赞量',
            'comment': '评论量',
            'transfer': '转发量',
            'share': '分享量',
        }

        /*
        * 几个图
        * */
        var sentimentChart;
        var emotionChart;
        var eventChart;
        var mapChart;

        const charts = {
            2: mapChart,
            3: eventChart,
        }

        const vm = new Vue({
            el: '#root',
            data: {
                // 左半拉
                'basic_data': {
                    'key': 'month', // 默认月环比
                    'kv': {
                        'month': '月环比',
                        'season': '季环比',
                        'half_year': '半年环比',
                        'year': '年环比'
                    },
                    'datas': null
                },
                'isLoaded': {
                    'basic': false,
                    'sentiment': false,
                    'emotion': false,
                    'blogs': false,
                    'event': false,
                    'map': false
                },
                'sentiment_data': [
                    {'name': 'example', 'value': 1}
                ],
                'emotion_data': [
                    {'name': 'example', 'value': 1}
                ],
                'event_data': {
                    'xAxis': ['2021-6-7', '2021-6-8', '2021-6-9', '2021-6-10', '2021-6-11', '2021-6-12'],
                    'yAxis': [502.84, 205.97, 332.79, 281.55, 398.35, 214.02]
                },
                // 中间：还没有
                // 右半拉
                orderBy: 'like_cnt',
                isGlobal: true,
                date: '全部在库数据',
                // 为了提升用户体验，讲查询结果做缓存，刷新整个页面之后获得最新数据，或者不刷新页面以最快的访问速度查看
                blogs: {
                    'like_cnt': [],
                    'comment_cnt': [],
                    'transfer_cnt': [],
                    'share_cnt': [],
                    'kv': {
                        'like_cnt': '点赞量',
                        'comment_cnt': '评论量',
                        'transfer_cnt': '转发量',
                        'share_cnt': '分享量'
                    },
                },
                mapData: null,
                dateRange: null,
                dateRangeStr: null
            },
            created() {
                this.fetchData(); // 在created钩子中调用fetchData方法
                this.selectOption(this.basic_data.key);
                this.handleItemClick(this.orderBy);
            },
            mounted() {
            },
            methods: {
                // 获取基本数据指标
                async getBaseData() {
                    that = this
                    that.isLoaded.basic = false;
                    await axios.get('/basic_data', {params: {key: 'month'}})
                        .then(response => {
                            that.basic_data.datas = response.data;
                            that.basic_data.key = 'month'; // 这里要补充
                            that.isLoaded.basic = true;
                        })
                        .catch(error => {
                            console.error(error)
                        })
                },
                // 获取emotion
                async getEmotionData() {
                    const timeBegin = this.formatDate(this.dateRange[0]);
                    const timeEnd = this.formatDate(this.dateRange[1]);
                    that = this
                    that.isLoaded.emotion = false;
                    await axios.get('/emotion?timeBegin=' + timeBegin + '&timeEnd=' + timeEnd)
                        .then(response => {
                            that.emotion_data = response.data; // 将请求返回的数据设置给data属性
                            that.isLoaded.emotion = true;
                            that.draw_emotion()
                        })
                        .catch(error => {
                            console.error(error);
                        });
                },
                // 获取sentiment
                async getSentimentData() {
                    const timeBegin = this.formatDate(this.dateRange[0]);
                    const timeEnd = this.formatDate(this.dateRange[1]);
                    that = this
                    that.isLoaded.sentiment = false;
                    await axios.get('/sentiment?timeBegin=' + timeBegin + '&timeEnd=' + timeEnd)
                        .then(response => {
                            that.sentiment_data = response.data; // 将请求返回的数据设置给data属性
                            that.isLoaded.sentiment = true;
                            that.draw_sentiment()
                        })
                        .catch(error => {
                            console.error(error);
                        });
                },
                // 获取事件走势数据
                async getEventTrend() {
                    const timeBegin = this.formatDate(this.dateRange[0]);
                    const timeEnd = this.formatDate(this.dateRange[1]);
                    that = this
                    await axios.get('/event_trend?timeBegin=' + timeBegin + '&timeEnd=' + timeEnd)
                        .then(response => {
                            that.event_data = response.data; // 将请求返回的数据设置给data属性
                            console.log(that.event_data)
                            that.isLoaded.event = true;
                            that.draw_trend()
                        })
                        .catch(error => {
                            console.error(error);
                        });
                },
                // 提前读入数据
                async fetchData() {
                    const that = this;
                    try {
                        // 获取基本数据指标
                        await axios.get('/basic_data', {params: {key: 'month'}})
                            .then(response => {
                                that.basic_data.datas = response.data;
                                that.basic_data.key = 'month'; // 这里要补充
                                that.isLoaded.basic = true;
                            })
                            .catch(error => {
                                console.error(error)
                            })
                        // 获取sentiment数据
                        await axios.get('/sentiment')
                            .then(response => {
                                that.sentiment_data = response.data; // 将请求返回的数据设置给data属性
                                that.isLoaded.sentiment = true;
                                that.draw_sentiment()
                            })
                            .catch(error => {
                                console.error(error);
                            });
                        // 获取emotion数据
                        await axios.get('/emotion')
                            .then(response => {
                                that.emotion_data = response.data; // 将请求返回的数据设置给data属性
                                that.isLoaded.emotion = true;
                                that.draw_emotion()
                            })
                            .catch(error => {
                                console.error(error);
                            });

                        // 事件走势图
                        await axios.get('/event_trend')
                            .then(response => {
                                that.event_data = response.data; // 将请求返回的数据设置给data属性
                                console.log(that.event_data)
                                that.isLoaded.event = true;
                                that.draw_trend()
                            })
                            .catch(error => {
                                console.error(error);
                            });

                        await axios.get('/blogs',
                            {
                                params: {
                                    pageSize: 10,
                                    pageNum: 1,
                                    orderBy: 'like_cnt'
                                }
                            })
                            .then(response => {
                                that.blogs['like_cnt'] = response.data;
                                that.isLoaded.blogs = true;
                            })
                            .catch(error => {
                                console.error(error)
                            })

                        // 世界地图
                        await $.ajax({
                            url: "../static/resource/jsons/word.json",
                            type: "GET",
                            dataType: "json",
                            success:
                                function (res) {
                                    that.mapData = res;
                                    $.ajax({
                                        url: "/RPC_world_map",
                                        type: "GET",
                                        dataType: "json",
                                        success:
                                            function (data_map) {
                                                console.log("begin")
                                                console.log(data_map.dataAddr)
                                                console.log(data_map.locations)
                                                console.log("end")
                                                that.mapData['dataArr'] = data_map.dataAddr;
                                                that.mapData['locations'] = data_map.locations;
                                                that.isLoaded.map = true;
                                                that.draw_world()
                                            },
                                        error() {
                                            alert("数据访问错误");
                                        }
                                    });
                                },
                            error() {
                                alert("地图生成错误");
                            }
                        });
                    } catch (error) {
                        console.error('Error fetching data:', error);
                    }
                },
                // 玫瑰图
                /* 情感饼图 */
                draw_sentiment() {
                    let that = this;
                    let sentimentContainer = document.getElementById('sentment_porporation');
                    sentimentChart = echarts.init(sentimentContainer);
                    let sentiment_option = {
                        legend: {
                            orient: 'vertical',
                            right: 'right',
                            y: 'center',
                            textStyle: {color: '#FFFFFF'},
                            formatter: function (name) {
                                var data_temp = sentiment_option.series[0].data; // 获取数据
                                var _sum = data_temp.reduce(function (accumulator, currentValue) {
                                    return accumulator + currentValue.value;
                                }, 0);
                                for (var i = 0; i < data_temp.length; i++) {
                                    if (data_temp[i].name === name) {
                                        // 使用数据中的数值和标签构建图例的显示格式
                                        return name + ': ' + Math.round(data_temp[i].value / _sum * 100) + '%: ' + data_temp[i].value + '条';
                                    }
                                }
                                return name;
                            }
                        },
                        toolbox: {
                            show: false,
                            feature: {
                                mark: {show: true},
                                dataView: {show: true, readOnly: false},
                                restore: {show: true},
                                saveAsImage: {show: true}
                            }
                        },
                        series: [
                            {
                                name: 'Nightingale Chart',
                                type: 'pie',
                                radius: [30, 50],
                                center: ['30%', '50%'],
                                roseType: 'area',
                                itemStyle: {
                                    borderRadius: 8
                                },
                                data: this.sentiment_data,
                                label: {
                                    show: true,
                                    // 设置字体样式
                                    textStyle: {
                                        color: function (params) {
                                            // 返回与扇形区域颜色相同的颜色值
                                            return params.color;
                                        }
                                    }
                                }
                            }
                        ]
                    };
                    sentimentChart.setOption(sentiment_option);
                    // 添加监听事件
                    window.addEventListener('resize', function () {
                        sentimentChart.resize();
                    });
                },
                /* 情绪饼图 */
                draw_emotion() {
                    let that = this;
                    let emotionContainer = document.getElementById('emotion_porporation');
                    emotionChart = echarts.init(emotionContainer);
                    let emotion_option = {
                        legend: {
                            orient: 'vertical',
                            right: 'right',
                            y: 'center',
                            textStyle: {color: '#FFFFFF'},
                            formatter: function (name) {
                                var data_temp = emotion_option.series[0].data; // 获取数据
                                var _sum = data_temp.reduce(function (accumulator, currentValue) {
                                    return accumulator + currentValue.value;
                                }, 0);
                                for (var i = 0; i < data_temp.length; i++) {
                                    if (data_temp[i].name === name) {
                                        // 使用数据中的数值和标签构建图例的显示格式
                                        return name + ': ' + Math.round(data_temp[i].value / _sum * 100) + '%: ' + data_temp[i].value + '条';
                                    }
                                }
                                return name;
                            }
                        },
                        toolbox: {
                            show: false,
                            feature: {
                                mark: {show: true},
                                dataView: {show: true, readOnly: false},
                                restore: {show: true},
                                saveAsImage: {show: true}
                            }
                        },
                        series: [
                            {
                                name: 'Emotion Porporation Chart',
                                type: 'pie',
                                radius: [30, 50],
                                center: ['30%', '50%'],
                                roseType: 'area',
                                itemStyle: {
                                    borderRadius: 8
                                },
                                data: this.emotion_data,
                                label: {
                                    show: true,
                                    // 设置字体样式
                                    textStyle: {
                                        color: function (params) {
                                            // 返回与扇形区域颜色相同的颜色值
                                            return params.color;
                                        }
                                    }
                                }
                            }
                        ]
                    };
                    emotionChart.setOption(emotion_option);
                    // 添加监听事件
                    window.addEventListener('resize', function () {
                        emotionChart.resize();
                    });
                },
                /* 世界地图 */
                draw_world() {
                    let that = this;
                    let mapContainer = document.getElementById('world_map');
                    // 初始化echarts实例
                    mapChart = echarts.init(mapContainer);
                    // 地图配置项
                    let option_map = {
                        title: {
                            show: 0,
                            text: "世界地图",
                            subtext: "示例",
                            left: "center",
                        },
                        tooltip: {
                            // hover时的提示框
                            trigger: "item",
                        },
                        visualMap: {
                            min: 0,
                            max: 150000,
                            left: "left",
                            top: "bottom",
                            text: ["高", "低"], // 文本，默认为数值文本
                            calculable: true,
                            color: ["#124782", "#D2E7FF"],
                            show: false,
                        },
                        series: [
                            {
                                name: "推文IP分布统计",
                                type: "map",
                                mapType: "world",
                                roam: true,
                                itemStyle: {
                                    emphasis: {label: {show: true}},
                                },
                                nameMap: that.mapData.namemap,
                                data: that.mapData.dataArr,
                                // 标记点数据
                                markPoint: {
                                    // 标记点的类型，可以自定义图片等
                                    symbol: 'pin',
                                    symbolSize: 10,
                                    label: {
                                        show: true
                                    },
                                    // 省份的经纬度数据
                                    data: that.mapData.locations
                                }
                            },
                        ],
                    };
                    // 使用刚指定的配置项和数据显示图表
                    mapChart.setOption(option_map);
                    // 添加监听事件
                    window.addEventListener('resize', function () {
                        mapChart.resize();
                    });
                },
                /* 事件走势图 */
                draw_trend() {
                    let that = this;
                    let eventContainer = document.getElementById('event_trend');
                    eventChart = echarts.init(eventContainer)
                    let eventOption = {
                        backgroundColor: '#080b30',
                        legend: {
                            show: false
                        },
                        grid: { // 让图表占满容器
                            top: "20px",
                            left: "40px",
                            right: "20px",
                            bottom: "30px"
                        },
                        tooltip: {
                            trigger: 'axis',
                            axisPointer: {
                                type: 'shadow'
                            },
                            confine: true
                        },
                        toolbox: {
                            show: false,
                            feature: {
                                mark: {show: true},
                                dataView: {show: true, readOnly: false},
                                restore: {show: true},
                                saveAsImage: {show: true}
                            }
                        },
                        xAxis: [{
                            type: 'category',
                            splitLine: {
                                show: true,
                                lineStyle: {
                                    color: 'rgba(255,255,255,0.1)'
                                }
                            },
                            data: this.event_data.xAxis,
                        }],

                        yAxis: [{
                            type: 'value',
                            splitLine: {
                                show: true,
                                lineStyle: {
                                    color: 'rgba(255,255,255,0.1)'
                                }
                            },
                        }],

                        series: {
                            name: '注册总量',
                            type: 'line',
                            smooth: true, //是否平滑
                            /* showAllSymbol: true,
                            // symbol: 'image://./static/images/guang-circle.png',
                            symbol: 'circle',
                            symbolSize: 25,
                            */
                            lineStyle: {
                                normal: {
                                    color: "#6c50f3",
                                    shadowColor: 'rgba(0, 0, 0, .3)',
                                    shadowBlur: 0,
                                    shadowOffsetY: 5,
                                    shadowOffsetX: 5,
                                },
                            },
                            label: {
                                show: true,
                                position: 'top',
                                textStyle: {
                                    color: '#6c50f3',
                                }
                            },
                            itemStyle: {
                                color: "#6c50f3",
                                borderColor: "#fff",
                                borderWidth: 3,
                                shadowColor: 'rgba(0, 0, 0, .3)',
                                shadowBlur: 0,
                                shadowOffsetY: 2,
                                shadowOffsetX: 2,
                            },
                            tooltip: {
                                show: false
                            },
                            areaStyle: {
                                normal: {
                                    color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                                        offset: 0,
                                        color: 'rgba(74,145,247,0.5)'
                                    },
                                        {
                                            offset: 1,
                                            color: 'rgba(74,145,247,0.01)'
                                        }
                                    ], false),
                                }
                            },
                            data: this.event_data.yAxis
                        }
                    };
                    let time = ""
                    //点击x轴线
                    eventChart.getZr().on('click', params => {
                        that.isLoaded.blogs = false;
                        // 变为区域查找
                        that.isGlobal = false;
                        const pointInPixel = [params.offsetX, params.offsetY]
                        if (eventChart.containPixel('grid', pointInPixel)) {
                            const xIndex = eventChart.convertFromPixel({seriesIndex: 0}, [params.offsetX, params.offsetY])[0]
                            time = eventOption.xAxis[0].data[xIndex]
                            // eventChart.resize();
                            console.log(time)
                            console.log("根据时间查询数据")
                            that.date = time
                            // TODO：这里要把时间返回去
                            axios.get('/blogs_date',
                                {
                                    params: {
                                        pageSize: 10,
                                        pageNum: 1,
                                        orderBy: that.orderBy,
                                        date: that.date
                                    }
                                })
                                .then(response => {
                                    that.blogs[that.orderBy] = response.data;
                                    that.isLoaded.blogs = true;
                                })
                                .catch(error => {
                                    console.error(error)
                                })
                        }
                    })
                    //点击x轴坐标
                    eventChart.on('click', 'xAxis.category', function (params, node) {
                        time = params.value
                        eventChart.resize();
                        console.log(time)
                    });
                    eventChart.setOption(eventOption);
                    // 添加监听事件
                    window.addEventListener('resize', function () {
                        eventChart.resize();
                    });
                },
                // 环比依据
                selectOption(optionSelected) {
                    btns = document.getElementById('btn_group').children;
                    for (var i = 0; i < btns.length; i++) {
                        let value_temp = btns[i].getAttribute('value');
                        console.log(value_temp)
                        if (value_temp === optionSelected) {
                            console.log("找到啦")
                            btns[i].style.backgroundColor = '#3f9ffc';
                            btns[i].style.color = '#FFFFFF';
                        } else {
                            console.log("找不到")
                            btns[i].style.backgroundColor = ''; // 将 'your-color' 替换为您想要的背景色
                            btns[i].style.color = '';
                        }
                    }
                    this.basic_data.key = optionSelected;
                    let that = this;
                    that.isLoaded.basic = false;
                    // 获取基本数据指标
                    axios.get('/basic_data', {params: {key: optionSelected}})
                        .then(response => {
                            that.basic_data.datas = response.data;
                            that.isLoaded.basic = true;
                        })
                        .catch(error => {
                            console.error(error)
                        })
                },
                // 排序依据
                handleItemClick(orderBy) {
                    /* 排序依据 */
                    console.log(orderBy);
                    btns = document.getElementsByClassName('parallelogram')
                    console.log(btns)
                    for (var i = 0; i < btns.length; i++) {
                        let value_temp = btns[i].getAttribute('value');
                        console.log(value_temp)
                        if (value_temp === orderBy) {
                            console.log("找到啦")
                            btns[i].style.background = 'linear-gradient(to right, #1abfdd 30%, #3293e1 70%)'; // 将 'your-color' 替换为您想要的背景色
                        } else {
                            console.log("找不到")
                            btns[i].style.background = ''; // 将 'your-color' 替换为您想要的背景色
                        }
                    }
                    this.orderBy = orderBy;
                    let that = this;
                    console.log("undefined???")
                    console.log(that.blogs[orderBy])
                    if (that.blogs[orderBy].length === 0 || !that.isGlobal) {
                        that.isLoaded.blogs = false;
                        console.log("我看看")
                        console.log(that.blogs[orderBy])
                        if (that.isGlobal) {
                            axios.get('/blogs', {
                                params: {
                                    pageSize: 10,
                                    pageNum: 1,
                                    orderBy: orderBy
                                }
                            })
                                .then(response => {
                                    that.blogs[orderBy] = response.data;
                                    that.isLoaded.blogs = true;
                                })
                                .catch(error => {
                                    console.error(error)
                                })
                        } else {
                            axios.get('/blogs_date',
                                {
                                    params: {
                                        pageSize: 10,
                                        pageNum: 1,
                                        orderBy: that.orderBy,
                                        date: that.date
                                    }
                                })
                                .then(response => {
                                    that.blogs[orderBy] = response.data;
                                    that.isLoaded.blogs = true;
                                })
                                .catch(error => {
                                    console.error(error)
                                })
                        }
                    }
                },
                // 计算粉丝数
                formatFansValue(value) {
                    // 进行计算并保留两位小数
                    return (value / 1000000).toFixed(4);
                },

                async download(blockIndex) {
                    console.log(blockIndex)
                    // 消息提示
                    this.$message({
                        message: '等待数据下载',
                        type: 'success'
                    });
                    if (blockIndex === 1) {
                        console.log("环比计算")
                        let month_temp = null;
                        let season_temp = null;
                        let halfy_temp = null;
                        let year_temp = null;
                        await axios.get('/basic_data', {params: {key: "month"}})
                            .then(response => {
                                month_temp = response.data;
                            })
                            .catch(error => {
                                console.error(error)
                            })
                        await axios.get('/basic_data', {params: {key: "season"}})
                            .then(response => {
                                season_temp = response.data;
                            })
                            .catch(error => {
                                console.error(error)
                            })
                        await axios.get('/basic_data', {params: {key: "half_year"}})
                            .then(response => {
                                halfy_temp = response.data;
                            })
                            .catch(error => {
                                console.error(error)
                            })
                        await axios.get('/basic_data', {params: {key: "year"}})
                            .then(response => {
                                year_temp = response.data;
                            })
                            .catch(error => {
                                console.error(error)
                            })
                        let format_str = [
                            {
                                "类型": "月环比",
                                "推文数目变化": month_temp[0].data.trend + '%',
                                "点赞数目变化": month_temp[1].data.trend + '%',
                                "国家地区数变化": month_temp[2].data.trend + '%',
                            },
                            {
                                "类型": "季环比",
                                "推文数目变化": season_temp[0].data.trend + '%',
                                "点赞数目变化": season_temp[1].data.trend + '%',
                                "国家地区数变化": season_temp[2].data.trend + '%',
                            },
                            {
                                "类型": "半年环比",
                                "推文数目变化": halfy_temp[0].data.trend + '%',
                                "点赞数目变化": halfy_temp[1].data.trend + '%',
                                "国家地区数变化": halfy_temp[2].data.trend + '%',
                            },
                            {
                                "类型": "年环比",
                                "推文数目变化": year_temp[0].data.trend + '%',
                                "点赞数目变化": year_temp[1].data.trend + '%',
                                "国家地区数变化": year_temp[2].data.trend + '%',
                            }]
                        this.JSONToExcelConvertor(format_str, "基本数据指标.xlsx", false, false)
                    }
                    if (blockIndex === 2) {
                        let imageData = mapChart.getConnectedDataURL({
                            type: 'png',
                            backgroundColor: '#011838',
                            pixelRatio: 5, // 设置像素比例，以提高图像质量
                        });
                        let downloadLink = document.createElement('a');
                        downloadLink.href = imageData;
                        downloadLink.download = 'chart.png';
                        // 触发下载
                        downloadLink.click();
                    }
                    if (blockIndex === 3) {
                        let imageData = eventChart.getConnectedDataURL({
                            type: 'png',
                            backgroundColor: '#011838',
                            pixelRatio: 5, // 设置像素比例，以提高图像质量
                        });
                        let downloadLink = document.createElement('a');
                        downloadLink.href = imageData;
                        downloadLink.download = 'chart.png';
                        // 触发下载
                        downloadLink.click();
                    }
                    if (blockIndex === 4) {
                        this.JSONToExcelConvertor(this.blogs[this.orderBy], "热点推文_" + this.blogs.kv[this.orderBy] + ".xlsx", false, false)
                    }
                },
                // json2excel
                /**
                 * JS转成ex文件，前端进行导出
                 * @param {*} JSONData  JSON数据
                 * @param {*} FileName   你希望导出文件的文件名
                 * @param {*} title     你希望的字段名也就是表头，一般情况下直接，没有特殊需求的话直接填入false就好
                 * @param {*} filter   你希望过滤的行数   如果没有也直接填入false就好
                 */
                JSONToExcelConvertor(JSONData, FileName, title, filter) {
                    if (!JSONData)
                        return;
                    //转化json为object
                    let arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
                    let excel = "<table>";
                    //设置表头
                    let row = "<tr>";
                    if (title) {
                        //使用标题项
                        for (var i in title) {
                            row += "<th align='center'>" + title[i] + '</th>';
                        }
                    } else {
                        //不使用标题项
                        for (var i in arrData[0]) {
                            row += "<th align='center'>" + i + '</th>';
                        }
                    }
                    excel += row + "</tr>";
                    //设置数据
                    for (var i = 0; i < arrData.length; i++) {
                        let row = "<tr>";
                        for (var index in arrData[i]) {
                            //判断是否有过滤行
                            if (filter) {
                                if (filter.indexOf(index) == -1) {
                                    var value = arrData[i][index] == null ? "" : arrData[i][index];
                                    row += '<td>' + value + '</td>';
                                }
                            } else {
                                var value = arrData[i][index] == null ? "" : arrData[i][index];
                                row += "<td align='center'>" + value + "</td>";
                            }
                        }
                        excel += row + "</tr>";
                    }
                    excel += "</table>";

                    //下面是构建文件的代码
                    var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:excel' xmlns='http://www.w3.org/TR/REC-html40'>";
                    excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
                    excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';
                    excelFile += '; charset=UTF-8">';
                    excelFile += "<head>";
                    excelFile += "<!--[if gte mso 9]>";
                    excelFile += "<xml>";
                    excelFile += "<x:ExcelWorkbook>";
                    excelFile += "<x:ExcelWorksheets>";
                    excelFile += "<x:ExcelWorksheet>";
                    excelFile += "<x:Name>";
                    excelFile += "{worksheet}";
                    excelFile += "</x:Name>";
                    excelFile += "<x:WorksheetOptions>";
                    excelFile += "<x:DisplayGridlines/>";
                    excelFile += "</x:WorksheetOptions>";
                    excelFile += "</x:ExcelWorksheet>";
                    excelFile += "</x:ExcelWorksheets>";
                    excelFile += "</x:ExcelWorkbook>";
                    excelFile += "</xml>";
                    excelFile += "<![endif]-->";
                    excelFile += "</head>";
                    excelFile += "<body>";
                    excelFile += excel;
                    excelFile += "</body>";
                    excelFile += "</html>";
                    var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);
                    //创建一个a标签
                    var link = document.createElement("a");
                    //给a标签一个路径
                    link.href = uri;
                    //为了防止这个a标签显示在视图上，需要先把他隐藏
                    link.style = "visibility:hidden";
                    //为文件添加后缀名，告诉他这是一个ex文件
                    link.download = FileName + ".xls";
                    //把a标签添加到body上
                    document.body.appendChild(link);
                    //触发a标签，等于访问这个文件地址，实现文件下载
                    link.click();
                    //文件下载完毕后删除a标签，以免对DOM产生冗余
                    document.body.removeChild(link);
                },
                // 日期范围转换
                updateQueryString() {
                    if (this.dateRange && this.dateRange.length === 2) {
                        const timeBegin = this.formatDate(this.dateRange[0]);
                        const timeEnd = this.formatDate(this.dateRange[1]);
                        this.dateRangeStr = `timeBegin=${timeBegin}&timeEnd=${timeEnd}`;
                        console.log("dateRange" + this.dateRangeStr)
                    } else {
                        this.dateRangeStr = '';
                        console.log("dateRange" + this.dateRangeStr)
                    }
                },
                formatDate(date) {
                    const year = date.getFullYear();
                    const month = (date.getMonth() + 1).toString().padStart(2, '0');
                    const day = date.getDate().toString().padStart(2, '0');

                    return `${year}-${month}-${day}`;
                },
                pageSelect(pageIdx) {
                    console.log(pageIdx)
                    if (pageIdx === '1') {
                        // 内容分析
                        window.alert("正在加急开发中...")
                        // window.open("/page2")
                    } else if (pageIdx === '2') {
                        // 主题聚类
                        if (this.dateRangeStr === null) {
                            this.$message({
                                message: '请从右侧栏目选择日期范围',
                                type: 'info'
                            });
                            return;
                        }
                        window.open("http://10.126.62.38:5000/wordcloud?param=" + encodeURIComponent(vm.dateRangeStr))
                    } else if (pageIdx === '3') {
                        window.open("/page4")
                    } else if (pageIdx === '4') {
                        window.alert("正在加急开发中...")
                        // window.open("/page4")
                    }
                },
                // 更新数据
                async updateDataByDate() {
                    console.log("update")
                    await this.getEmotionData()
                    await this.draw_emotion()
                    await this.getSentimentData()
                    await this.draw_sentiment()
                    await this.getEventTrend()
                    await this.draw_trend()
                }
            },
            computed: {},
            watch: {}
        })
    </script>
    <script>
        // 下拉框切换页面
        function pageSelect(pageIdx) {
            console.log(pageIdx)
            if (pageIdx === '1') {
                window.open("/page1")
            } else if (pageIdx === '2') {
                window.open("/page2")
            } else if (pageIdx === '3') {
                window.open("http://10.126.62.38:5000/wordcloud?param=" + encodeURIComponent(vm.dateRangeStr))
            } else if (pageIdx === '4') {
                window.open("/page4")
            }
        }
    </script>
{% endblock body_block %}